import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;

public class UDBC {
    private static final String url = "jdbc:mysql://127.0.0.1:3306/messageWall?useSSL=false&characterEncoding=utf8";
    private static final String user = "root";
    private static  final String passWord = "123456";
    public static volatile DataSource dataSource = null;

    //创建数据库连接
    public static DataSource getDataSource(){
        if (dataSource == null) {
            synchronized (UDBC.class) {
                if (dataSource == null) {
                    dataSource = new MysqlDataSource();
                    ((MysqlDataSource)dataSource).setUrl(url);
                    ((MysqlDataSource)dataSource).setUser(user);
                    ((MysqlDataSource)dataSource).setPassword(passWord);
                }
            }
        }
        return dataSource;
    }
    //连接数据库
    public static Connection getCon() throws SQLException {
        return getDataSource().getConnection();
    }
    //关闭资源
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) throws SQLException {
        if (resultSet != null){
            resultSet.close();
        }
        if (preparedStatement != null){
            preparedStatement.close();
        }
        if (connection != null){
            connection.close();
        }
    }
}
